<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
      label-position="left"
    >
      <el-form-item
        :label="$t('form.evaluation.nickname')"
        prop="appraiseUserId"
      >
        <el-input
          v-model="queryParams.nickName"
          :placeholder="$t('form.evaluation.enterUserNickname')"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="ele-Search"
          @click="handleQuery"
        >
          {{ $t("common.search") }}
        </el-button>
      </el-form-item>
    </el-form>

    <el-row
      :gutter="10"
      class="mb8"
    >
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="ele-Plus"
          @click="handleAssignUser"
        >
          {{ $t("form.evaluation.addEvaluate") }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          icon="ele-Plus"
          @click="handleShowImportAppraise"
        >
          {{ $t("form.evaluation.batchImport") }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="ele-Delete"
          :disabled="multiple"
          @click="handleDelete"
        >
          {{ $t("form.evaluation.delete") }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="ele-Download"
          @click="handleExport"
        >
          {{ $t("form.evaluation.export") }}
        </el-button>
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @query-table="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="evalAppraiseList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
      />
      <el-table-column
        :label="$t('form.evaluation.evaluate')"
        align="center"
        prop="appraiseUserId"
      >
        <template #default="scope">
          <t-avatar
            :size="30"
            :url="scope.row.appraiseUser!.avatar"
            :name="scope.row.appraiseUser.nickName"
          ></t-avatar>
          {{ scope.row.appraiseUser!.nickName }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        v-for="role in evalRoleList"
        :key="role.id"
        :label="role.name"
      >
        <template #default="scope">
          <span
            v-for="(re, index) in getEvalRoleReviewerList(role.id, scope.row.reviewerList)"
            :key="re.id"
          >
            <el-tag
              size="small"
              class="ml6"
              v-if="index < 2"
            >
              {{ re.nickName }}
            </el-tag>
          </span>
          <el-link
            class="ml10"
            type="primary"
            @click="handleShowUserInfo(scope.row, role.id)"
          >
            {{ $t("form.evaluation.details") }}({{ getEvalRoleReviewerList(role.id, scope.row.reviewerList)!.length }})
          </el-link>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="$t('form.evaluation.weightGroup')"
      >
        <template #default="scope">
          <el-select
            v-model="scope.row.weightGroupId"
            size="default"
            @change="handleWeightChange(scope.row)"
          >
            <el-option
              v-for="item in evalWeightGroupList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('form.evaluation.operation')"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="ele-User"
            @click="handleSettingReviewer(scope.row)"
          >
            {{ $t("form.evaluation.setEvaluator") }}
          </el-button>
          <el-button
            link
            type="primary"
            icon="ele-Delete"
            @click="handleDelete(scope.row)"
          >
            {{ $t("form.evaluation.delete") }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.current"
      v-model:limit="queryParams.size"
      @pagination="getList"
    />

    <el-dialog
      :title="title"
      v-model="open"
      width="500px"
      append-to-body
    >
      <el-form
        ref="evalAppraiseRef"
        label-width="80px"
        label-position="top"
      >
        <el-form-item
          v-for="role in evalRoleList"
          :key="role.id"
          :label="role.name"
          prop="role.id"
        >
          <div>
            <el-tag
              v-for="user in reviewerMap[role.id || 0]"
              :key="user.id"
              size="default"
              class="mr10"
              closable
              @close="handleRemoveReviewer(role.id, user.id)"
            >
              {{ user.nickName }}
            </el-tag>

            <div class="mt10">
              <el-button
                size="default"
                icon="ele-Plus"
                @click="handleAddReviewer(role.id)"
              >
                {{ $t("form.evaluation.addEvaluator") }}
              </el-button>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            :loading="buttonLoading"
            type="primary"
            @click="handleSubmitReviewerList"
          >
            {{ $t("common.enter") }}
          </el-button>
          <el-button @click="open = false">{{ $t("common.cancel") }}</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      :title="$t('form.evaluation.userDetails')"
      v-model="userInfoVisible"
      width="700px"
      append-to-body
    >
      <el-table :data="currentRoleUserList">
        <el-table-column
          prop="nickName"
          :label="$t('form.evaluation.nickname')"
          align="center"
          width="180"
        >
          <template #default="scope">
            <t-avatar
              :size="30"
              :url="scope.row!.avatar"
              :name="scope.row.nickName"
            ></t-avatar>
            <span>{{ scope.row!.nickName }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="userName"
          :label="$t('form.evaluation.account')"
          align="center"
          width="180"
        />
        <el-table-column
          prop="phonenumber"
          :label="$t('form.evaluation.phoneNumber')"
          align="center"
        />
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="userInfoVisible = false">{{ $t("common.cancel") }}</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      :title="$t('form.evaluation.batchImport')"
      v-model="importAppraiseVisible"
      width="600px"
      append-to-body
    >
      <el-upload
        ref="importUploadRef"
        :action="importAppraiseUrl"
        :headers="getUploadHeader()"
        :limit="1"
        :data="importUpdateData"
        :on-success="handleImportSuccess"
        accept=".xlsx, .xls"
        drag
      >
        <el-icon>
          <ele-Upload />
        </el-icon>
        <div class="el-upload__text">
          {{ $t("form.evaluation.batchImport") }}
        </div>
        <template #tip>
          <div class="el-upload__tip">
            {{ $t("form.evaluation.importTips1") }}
            <el-link
              style="font-size: 12px"
              type="primary"
              @click="importTemplate"
            >
              {{ $t("form.evaluation.downImportTemplate") }}
            </el-link>
          </div>
          <div class="el-upload__tip">{{ $t("form.evaluation.importTips2") }}</div>
          <div class="el-upload__tip text-danger">
            {{ $t("form.evaluation.importTips3") }}
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="importAppraiseVisible = false">{{ $t("common.cancel") }}</el-button>
        </div>
      </template>
    </el-dialog>
    <user-choose-table
      ref="userChooseTableRef"
      @submit="handleSubmitAssignUser"
    />
  </div>
</template>

<script setup name="EvalAppraise" lang="ts">
import {
  addEvalAppraise,
  delEvalAppraise,
  downloadTemplate,
  EvalAppraise,
  EvalAppraiseReviewer,
  exportAppraise,
  listEvalAppraise,
  setReviewerUser,
  updateEvalAppraise
} from "@/api/evaluation/appraise";
import { computed, ref } from "vue";
import { MessageUtil } from "@/utils/messageUtil";
import { ElMessageBox } from "element-plus";
import UserChooseTable from "@/views/system/user/chooseTable.vue";
import { i18n } from "@/i18n";
import { useRoute } from "vue-router";
import { evaluationHook } from "@/views/form/evaluation/useEvaluation";
import TAvatar from "@/components/TAvatar/index.vue";
import { UserEntity } from "@/api/system/user";
import { download } from "@/utils/tduck";
import { getUploadHeader } from "@/utils/uploadFile";
import { downloadImportTemplateRequest } from "@/api/project/data";
import { baseUrl } from "@/utils/auth";

const evalAppraiseList = ref<EvalAppraise[]>([]);
const open = ref(false);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<number[]>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const userInfoVisible = ref(false);
const emit = defineEmits(["refresh"]);

const route = useRoute();

const queryParams = ref({
  current: 1,
  size: 10,
  nickName: "",
  formKey: route.query.key as string
});

/** 查询被评人列表 */
const getList = () => {
  loading.value = true;
  listEvalAppraise(queryParams.value).then(response => {
    evalAppraiseList.value = response.data.records;
    total.value = response.data.total;
    loading.value = false;
  });
};

const userChooseTableRef = ref<InstanceType<typeof UserChooseTable> | null>(null);

const handleAssignUser = () => {
  userSelectType.value = 1;
  userChooseTableRef.value.showDialog([]);
};

// 用户选择类型  1. 被评价人添加 2. 审核人添加
const userSelectType = ref(1);
const reviewerMap = ref<Record<number, any[]>>({});
const currentEvalAppraise = ref<EvalAppraise>();

const reviewerRoleId = ref(0);

const handleSubmitAssignUser = (val: any) => {
  if (userSelectType.value === 1) {
    const userIdList = val.map((item: any) => item.id);
    addEvalAppraise({
      formKey: route.query.key as string,
      appraiseUserIdList: userIdList
    }).then(() => {
      MessageUtil.success(i18n.global.t("formI18n.all.success"));
      getList();
    });
  } else if (userSelectType.value === 2) {
    reviewerMap.value[reviewerRoleId.value] = val;
  }
};

const handleRemoveReviewer = (roleId: number, userId: number) => {
  reviewerMap.value[roleId] = reviewerMap.value[roleId].filter(item => item.id !== userId);
};

const handleSubmitReviewerList = () => {
  // 遍历评估者 是否有选中任意
  const reviewerList = Object.values(reviewerMap.value).flat();
  if (reviewerList.length) {
    const data = {
      id: currentEvalAppraise.value!.id,
      formKey: route.query.key as string,
      appraiseUserId: currentEvalAppraise.value?.appraiseUserId,
      reviewerList: Object.keys(reviewerMap.value).map((roleId: any) => {
        return {
          roleId: roleId,
          userIdList: reviewerMap.value[roleId].map((item: any) => item.id)
        };
      })
    };
    setReviewerUser(data).then(() => {
      MessageUtil.success(i18n.global.t("form.evaluation.setSuccess"));
      open.value = false;
      getList();
      emit("refresh");
    });
  } else {
    MessageUtil.error(i18n.global.t("form.evaluation.selectEvaluator"));
  }
};

const { evalRoleList, evalWeightGroupList } = evaluationHook;

// 获取评价人列表
const getEvalRoleReviewerList = (roleId: number | undefined, reviewerList: EvalAppraiseReviewer[]): UserEntity[] => {
  if (reviewerList && reviewerList.length) {
    return (reviewerList!.find(item => item.roleId == roleId)?.userList as UserEntity[]) || [];
  }
  return [];
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.current = 1;
  getList();
};

// 多选框选中数据
const handleSelectionChange = (selection: EvalAppraise[]) => {
  ids.value = selection.map((item: EvalAppraise) => item.id || 0);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

const handleWeightChange = (row: EvalAppraise) => {
  const data = {
    id: row.id,
    weightGroupId: row.weightGroupId
  };
  updateEvalAppraise(data).then(() => {
    MessageUtil.success(i18n.global.t("form.evaluation.modifySuccess"));
  });
};

const handleSettingReviewer = (row: EvalAppraise) => {
  open.value = true;
  title.value = i18n.global.t("form.evaluation.setEvaluator");
  userSelectType.value = 2;
  currentEvalAppraise.value = row;
  reviewerMap.value = {};
  if (row.reviewerList) {
    row.reviewerList.forEach((item: any) => {
      reviewerMap.value[item.roleId] = item.userList;
    });
  }
};

const handleAddReviewer = (roleId?: number) => {
  if (roleId) {
    reviewerRoleId.value = roleId;
    console.log(reviewerMap.value[roleId]);
    userChooseTableRef.value.showDialog(reviewerMap.value[roleId] || []);
  }
};

/** 删除按钮操作 */
const handleDelete = (row: EvalAppraise) => {
  const _ids = row.id || ids.value;
  ElMessageBox.confirm(i18n.global.t("form.evaluation.confirmDeleteEvaluateNumber"))
    .then(function () {
      loading.value = true;
      return delEvalAppraise(_ids);
    })
    .then(() => {
      loading.value = true;
      getList();
      emit("refresh");
      MessageUtil.success(i18n.global.t("form.evaluation.deleteSuccess"));
    })
    .catch(() => {})
    .finally(() => {
      loading.value = false;
    });
};

/** 导出按钮操作 */
const handleExport = () => {
  exportAppraise(queryParams.value).then(res => {
    download(res, i18n.global.t("form.evaluation.evaluateListXlsx", { no: new Date().getTime() }));
  });
};

getList();

const currentRoleUserList = ref<UserEntity[]>([]);

const handleShowUserInfo = (row: EvalAppraise, roleId: number) => {
  userInfoVisible.value = true;
  currentRoleUserList.value = getEvalRoleReviewerList(roleId, row.reviewerList || []);
};

const importAppraiseVisible = ref(false);

const handleShowImportAppraise = () => {
  importAppraiseVisible.value = true;
  if (importUploadRef.value) {
    importUploadRef.value!.clearFiles();
  }
};

const importAppraiseUrl = ref(baseUrl + "/form/eval/appraise/import");

const importUpdateData = computed(() => {
  return {
    formKey: route.query.key as string
  };
});

const importTemplate = () => {
  downloadTemplate().then(response => {
    download(response, "导入模板");
  });
};

const importUploadRef = ref(null);

const handleImportSuccess = (response: any) => {
  importAppraiseVisible.value = false;
  ElMessageBox.alert(response.data, i18n.global.t("form.fileUpload.tip6"), { dangerouslyUseHTMLString: true });
  getList();
  emit("refresh");
};
</script>
